#!/usr/bin/env bash
# Requires GNU sed
# Hack specs to workaround differences in how RPM 5 and RPM 4 work with docs:
# rpm5 automatically includes %_defaultdocdir/%name, but rpm4 does not
# Note: "%optional" is not upstream in rpm4, it is added by a patch from OpenMandriva

# $1 - directory with git
if [ -z "$1" ]; then
	exit 1
fi

set -eu
trap popd exit

LOG="${LOG:-/tmp/add-optional-doc-files.log}"
BRANCH="${BRANCH:-rosa2019.05}"
dir0="${dir0:-$PWD}"
. "${dir0}/funcs.sh"
# пробел специально!
# OPTIONAL="" для отключения %optional
OPTIONAL="${OPTIONAL:-%optional }"

pushd "$1"

git reset --hard
git fetch --all
if ! git checkout ${BRANCH} ; then
	echo "FAIL;${1};no-branch-${BRANCH}" | tee -a "$LOG"
	exit 1
fi
git reset origin/${BRANCH} --hard

while read -r specfile
do
	if ! test -f "$specfile"; then
		echo "FAIL;${1};no-file-${specfile}" | tee -a "$LOG"
		continue
	fi
	if grep -qE "^%.*{_defaultdocdir}/%{name}|^%.*_defaultdocdir/%name" "$specfile" ; then
		echo "SKIP;${1};docdir-already-in-spec" | tee -a "$LOG"
		continue
	fi
	cp "${specfile}" "${specfile}.new"
	added=0
	lineshift=0
	linenum=0
	while read -r line
	do
		#echo -e "$line" >> "${specfile}.new"
		linenum=$((++linenum))
		# https://stackoverflow.com/a/4438318
		# Work with the main package only, not subpackages
		if echo "$line" | sed 's/[ \t]*$//' | grep -q '^%files$'; then
			# https://stackoverflow.com/a/6537587
			line_to_add_num="$(echo $((++linenum))+${lineshift} | bc)"
			sed -i -e "${line_to_add_num}i${OPTIONAL}%doc %{_defaultdocdir}/%{name}/*" "${specfile}.new"
			lineshift=$((++lineshift))
			echo "ADDED;${1};added-doc-files-on-line-${line_to_add_num}" | tee -a "$LOG"
			added=1
		fi
	done < <(cat "$specfile")
	if [ "$added" = 1 ]; then
		if diff -u "${specfile}" "${specfile}.new" | grep -v '^\-\-\-' | grep -q '^\-' ; then
			echo "FAIL;${1};changes-of-existing-lines-detected" | tee -a "$LOG"
			continue
		fi
		mv "${specfile}.new" "${specfile}.new2"
		rm -f "${specfile}"
		mv "${specfile}.new2" "${specfile}"
		GIT_ADD_ALL=0
		git add "${specfile}"
		COMMIT_MSG="bot: rpm5 -> rpm4 (11)  

(11) Try to fix packages which ship additional docs
---------------------------------------------------
     It is a difference between rpm5 and rpm4:
     rpm5 automatically includes %_defaultdocdir/%name, but rpm4 does not.
---------------------------------------------------
These change is made by script add-optional-doc-files.sh from https://gitlab.com/abf-mirror/abf-mirror-scripts
Contact m.novosyolov@rosalinux.ru in case of problems
"
		if ! LC_ALL=POSIX git status | grep -q 'nothing to commit'; then
			_git_commit
			_git_push
		fi
	fi
done < <(ls -1v *.spec)
